package com.dkd.manage.task.allocator.model;

import lombok.Data;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Data
public class PerformanceMonitor {
    private ConcurrentHashMap<String, AtomicLong> algorithmExecutionCount = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, AtomicLong> algorithmSuccessCount = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, Double> algorithmAverageScore = new ConcurrentHashMap<>();

    public void recordAlgorithmPerformance(String algorithmName, double score, boolean success) {
        algorithmExecutionCount.computeIfAbsent(algorithmName, k -> new AtomicLong(0)).incrementAndGet();
        if (success) {
            algorithmSuccessCount.computeIfAbsent(algorithmName, k -> new AtomicLong(0)).incrementAndGet();
        }

        // 更新平均分
        algorithmAverageScore.merge(algorithmName, score, (oldVal, newVal) -> (oldVal + newVal) / 2);
    }

    public double getAlgorithmSuccessRate(String algorithmName) {
        AtomicLong execCount = algorithmExecutionCount.get(algorithmName);
        AtomicLong successCount = algorithmSuccessCount.get(algorithmName);

        if (execCount == null || execCount.get() == 0) {
            return 0.5; // 默认成功率
        }

        return (double) successCount.get() / execCount.get();
    }
}